<?php
/**
 * User: 自娱自乐自逍遥
 * Date: 14-10-14
 * Time: 上午11:01
 */

namespace Member\Model;


use Think\Model;

class MemberModel extends Model{

    protected $_validate = array(
        array('username','require','用户名不能为空!', self::MUST_VALIDATE),
        array('username','','用户名已存在!',self::EXISTS_VALIDATE,'unique',1),
        array('nickname','require','昵称不能为空!'),
        array('password','require','密码不能为空!', self::EXISTS_VALIDATE),
        array('sex',array('M','W','U'),'性别不对!',self::VALUE_VALIDATE,'in'),
    );

    protected $_auto = array(
        array('password', 'sign_password', self::MODEL_BOTH, 'callback'),
        array('salt', 'salt', self::MODEL_BOTH, 'callback')
    );

    /**
     * 用户密码加密盐
     * @param int $length
     * @return string
     */
    public function salt($length = 6){
        static $salt;
        if(empty($salt))$salt = random($length);
        return $salt;
    }

    /**
     * 密码加密
     * @param $pwd
     * @return string
     */
    public function sign_password($pwd){
        $salt = $this->salt();
        return md5($pwd.$salt);
    }

    /**
     * 验证用户密码
     * @param $password string 明文密码
     * @param $data array 用户信息
     * @return bool
     */
    public function verify_password($password, $data){
        return $data['password'] === md5($password.$data['salt']);
    }

    /**
     * 用户信息
     * @param $where array|int
     * @return mixed
     */
    public function get_user_info($where){
        if(is_numeric($where)){
            $where = array($this->getPk()=>$where);
        }
        return $this->limit(1)->find(array('where'=>$where));
    }

    /**
     * 登陆
     * @param $username string|int 用户名或ID
     * @param $password string 密码
     * @return bool|mixed
     */
    public function login($username, $password){
        $where = '';
        if(is_numeric($username)){
            $where = array($this->getPk()=>$username);
        }else if(is_string($username)){
            $where = array('username'=>$username);
        }else{
            $this->error = '错误的用户名';
        }
        $data = $this->get_user_info($where);
        if($data && $this->verify_password($password, $data)){
            if($data['status'] != 1){
                $this->error = '用户被禁用';
                return false;
            }else{
                /*$this->setField(array(
                    'last_login_time'       => '',
                    'last_login_ip'         => ip2long(get_client_ip()),
                ));*/
                //TODO: 登陆日志
                $this->saveLoginStatus($data);
                return $data;
            }
        }else{
            $this->error = '用户验证失败';
            return false;
        }
    }

    /**
     * 登录,系统内部调用
     * @param $uid int 用户ID
     * @return bool|mixed
     */
    public function loginBy($uid){
        $data = $this->get_user_info($uid);
        if(!empty($info)){
            $this->saveLoginStatus($data);
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 保存登录状态
     * @param $data
     */
    protected function saveLoginStatus($data){
        $info = array(
            'uid'       => $data['uid'],
            'username'  => $data['username'],
            'nickname'  => $data['nickname'],
            'sex'       => $data['sex'],
            'last_login_time'   => time()
        );
        session('user_login_info', $info);
        session('user_login_sign', data_auth_sign($info));
    }

    public function get_login_info($key = ''){
        $info = session('user_login_info');
        if(!empty($key) && isset($info[$key])){
            return $info[$key];
        }
        return $info;
    }


    public function logout(){
        session('user_login_info', null);
        session('user_login_sign', null);
    }

    /** 验证用户是否登陆
     * @return bool
     */
    public function verify_login(){
        $info = session('user_login_info');
        $expired = C('USER_LOGIN_EXPIRED',null,0); //用户身份过期时间，单位秒
        if(empty($info) || !session('user_login_sign') === data_auth_sign($info) || ($expired && time() - $info['last_login_time'] > $expired)){
            return false;
        }
        return true;
    }

    public function __get($name){
        if($name === 'is_login'){
            return $this->verify_login();
        }else{
            return parent::__get($name);
        }
    }
} 